package com.permissionmanager.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.permissionmanager.entity.Notice;
import com.permissionmanager.entity.Page;
import com.permissionmanager.exception.ServiceException;
import com.permissionmanager.mapper.NoticeMapper;
import com.permissionmanager.service.NoticeService;
import com.permissionmanager.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * notice业务层
 *
 */
@Service
@RequiredArgsConstructor
public class NoticeServiceImpl implements NoticeService {
    private final NoticeMapper noticeMapper;


    /**
     * 新增
     * @param notice 公告信息（不传id）
     */
    @Override
    public void add(Notice notice) {
        Integer userId = Objects.requireNonNull(JwtUtil.getCurrentUser()).getId();
        if (StrUtil.isBlank(notice.getTitle()) || StrUtil.isBlank(notice.getContent())) {
            throw new ServiceException("标题或内容为空！");
        }
        notice.setUserId(userId);
        notice.setTime(DateUtil.now());
        noticeMapper.add(notice);
    }



    /**
     * 修改
     * @param notice （title、content）
     */
    @Override
    public void update(Notice notice) {
        if(StrUtil.isBlank(notice.getTitle()) || StrUtil.isBlank(notice.getContent())){
            throw new ServiceException("标题或内容或发布为空!");
        }
        noticeMapper.update(notice);
    }

    /**
     * 分页查询
     */
    @Override
    public Page<Notice> findPage(Integer pageNum, Integer pageSize, String title, String username) {
        Integer skipNum = (pageNum - 1) * pageSize;
        Page<Notice> page = new Page<>();
        List<Notice> list = noticeMapper.findPage(skipNum, pageSize, title, username);
        page.setTList(list);
        page.setTotal(list.size());
        return page;
    }

    /**
     * 删除
     * @param id 传入的id
     */
    @Override
    public void del(Integer id) {
        noticeMapper.del(id);
    }

    /**
     * 导出
     */
    @Override
    public List<Notice> findNotice(List<Integer> idsArr, String title, String username, Integer open) {
        List<Notice> uList = new ArrayList<>();
        if (idsArr == null) {
            uList = noticeMapper.findNotice(null,title,username,open);
        } else {
            for (Integer id : idsArr) {
                uList.add(noticeMapper.findNotice(id, null, null,null).get(0));
            }
        }
        return uList;
    }
}
